Skip to content

Image

Base classes

Name Children Inherits
SerializeMixin
prettyqt.utils.serializemixin
PaintDeviceMixin
prettyqt.gui.paintdevice
QImage
PySide6.QtGui
QImage(self, /) -> None

⋔ Inheritance diagram

graph TD
  2320207063["gui.Image"]
  69336483["utils.SerializeMixin"]
  2751680898["builtins.object"]
  625385617["gui.PaintDeviceMixin"]
  3968184231["QtGui.QImage"]
  673956333["QtGui.QPaintDevice"]
  37984305["Shiboken.Object"]
  69336483 --> 2320207063
  2751680898 --> 69336483
  625385617 --> 2320207063
  2751680898 --> 625385617
  3968184231 --> 2320207063
  673956333 --> 3968184231
  37984305 --> 673956333
  2751680898 --> 37984305

🛈 DocStrings

Bases: SerializeMixin, PaintDeviceMixin, QImage

Hardware-independent image representation with direct access to the pixel data.

Source code in prettyqt/gui/image.py
class Image(serializemixin.SerializeMixin, gui.PaintDeviceMixin, gui.QImage):
    """Hardware-independent image representation with direct access to the pixel data."""

    def __setitem__(self, index: tuple[int, int], value):
        self.setPixel(index[1], index[0], value)

    def __getitem__(self, index: tuple[int, int]) -> int | list[int]:
        match index:
            case int() as row, int() as col:
                return self.pixel(col, row)
            case (row, col):
                rowcount = self.height()
                colcount = self.width()
                return [
                    self.pixel(j, i)
                    for i, j in helpers.iter_positions(row, col, rowcount, colcount)
                ]
            case _:
                raise TypeError(index)

    @classmethod
    def from_ndarray(cls, arr) -> Self:
        import numpy as np

        height, width, bytes_per_component = arr.shape
        if arr.dtype in {np.float32, np.float64}:
            arr = (255 * arr).round()
        arr = np.ascontiguousarray(arr, dtype=np.uint8)
        img = cls(
            arr.data,
            width,
            height,
            bytes_per_component * width,
            gui.QImage.Format.Format_RGB888,
        )
        img.__data = arr  # ty: ignore[missing-attribute]  # keeps the buffer alive
        return img

    def to_ndarray(
        self, fmt: FormatStr | gui.QImage.Format = "rgb888", channels: int = 3
    ):
        import numpy as np

        qimage = self.convert_to_format(fmt)
        width = qimage.width()
        height = qimage.height()
        ptr = qimage.constBits()
        if ptr is None:
            return np.empty((0, 0, channels), dtype=np.uint8)
        if API == "pyqt6":
            raw = ptr.asstring(qimage.sizeInBytes())  # ty: ignore[missing-attribute]
            arr = np.frombuffer(raw, dtype=np.uint8)
        else:
            arr = np.frombuffer(ptr, dtype=np.uint8)
        bytes_per_line = qimage.bytesPerLine()
        arr = arr.reshape((height, bytes_per_line))[:, : width * channels]
        return arr.reshape((height, width, channels)).copy()

    @classmethod
    def from_pil(cls, image) -> Self:
        # from https://github.com/python-pillow/Pillow/blob/main/src/PIL/ImageQt.py
        from PIL import ImageQt

        data = ImageQt._toqclass_helper(image)
        img = cls(data["data"], data["size"][0], data["size"][1], data["format"])
        if data["colortable"]:
            img.setColorTable(data["colortable"])
        img.__data = data["data"]  # ty: ignore[missing-attribute]  # keeps the buffer alive
        return img

    def to_pil(self):
        from PIL import Image as PILImage

        buffer = core.Buffer()
        buffer.open(core.Buffer.OpenModeFlag.ReadWrite)
        # PySide6's stub wants bytes, but only str works at runtime.
        self.save(buffer, "PNG")  # ty: ignore[no-matching-overload]
        return PILImage.open(io.BytesIO(buffer.data().data()))

    def invert_pixels(self, invert_alpha: bool = False):
        self.invertPixels(
            gui.QImage.InvertMode.InvertRgba
            if invert_alpha
            else gui.QImage.InvertMode.InvertRgb
        )

    def convert_to_format(self, fmt: FormatStr | gui.QImage.Format) -> Self:
        return type(self)(self.convertToFormat(FORMAT.get_enum_value(fmt)))

    def as_bytes(self) -> bytes:
        bits = self.bits()
        if bits is None:
            return b""
        if API == "pyqt6":  # sip.voidptr, the stubs only know PySide6's memoryview
            return bits.asstring(self.sizeInBytes())  # ty: ignore[missing-attribute]
        return bytes(bits)

:fa-brands-github: Show source on GitHub